import 'package:flutter/material.dart';
import 'package:listview/models/list_item.dart';
import 'package:listview/providers/list_provider.dart';
import 'package:provider/provider.dart';
import '../providers/list_provider.dart';
import '../widgets/list_item_card.dart';

class IconListScreen extends StatelessWidget {
  const IconListScreen({Key? key}) :super(key: key);

  @override
  Widget build(BuildContext context) {
    // 通过 Provider 获取状态
    final listProvider = Provider.of<ListProvider>(context);
    final items = listProvider.items;

    return Scaffold(
      appBar: AppBar(
          title: const Text("带图标的列表") ,
          actions :
          [
            IconButton   (
              icon:const  Icon
                (
                  Icons
                      .
                  refresh
              )
              ,
              onPressed
                  :
                  () {
             listProvider.shuffleItems();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text("列表已刷新")),
                );
              },)
          ]),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) =>
            ListItemCard(
              item: items[index],
              index: index,
              onTap: () => _handleItemTap(context,items[index]),
              onDelete: ()=>_deleteItem(context,index),
            ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed:()=> _addItem(context),
        child: const Icon(Icons.add),
      ),);
  }

  void _addItem(BuildContext context){
    final listProvider = Provider.of<ListProvider>(context,listen: false);
    final newIndex = listProvider.items.length +1;

    listProvider.addItem(
      ListItem("新项目 $newIndex", Icons.new_releases,
      Colors.primaries[newIndex%Colors.primaries.length])
    );
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text("已添加新项目"))
    );
  }

  void _handleItemTap(BuildContext context,ListItem item){
    Navigator.pushNamed(context, '/detail',arguments: item);
  }

  void _deleteItem(BuildContext context,int index){
    final listProvider = Provider.of<ListProvider>(context,listen: false);
    final deleteItem = listProvider.items[index];
    listProvider.removeItem(index);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text("已删除：${deleteItem.title}"),
      action: SnackBarAction(
        label: "撤销",
        onPressed: ()=>listProvider.addItem(deleteItem),
      ),),
    );

  }
}